package com.readboottest.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zhanghuiyong
 * @创建时间 2019年02月20日
 * @描述: 时间处理工具
 **/

public class DateUtil {
    public static void main(String[] args) throws ParseException {
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        Date date1 = new Date();
//
//        Calendar c = Calendar.getInstance();
//        c.set(Calendar.MONTH, c.get(Calendar.MONTH) - 2);
//        c.set(Calendar.DATE, 1);
//        c.set(Calendar.HOUR_OF_DAY, 0);
//        c.set(Calendar.MINUTE, 0);
//        c.set(Calendar.SECOND, 0);
//        Date time = c.getTime();
//        String format2 = format.format(time);
//        System.out.println(format2);

        Date silentDate = getSilentDateNew(new Date(), 31);
        System.out.println(silentDate);


    }

    /**
     * 获取格式化的时间
     *
     * @param pattern
     * @param date
     * @return
     */
    public static Date getDate(String pattern, String date) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            return format.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取三个月前的日期
     *
     * @return
     */
    public static Date getSilentDateNew(Date beginDate, int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(beginDate);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - num);
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 沉默用户统计需求：获取N天之前的指定日期格式的时间
     *
     * @param beginDate 开始时间
     * @param pattern   pattern 日期格式
     * @param num       当前日期的前N天
     * @return
     */
    public static Date getSilentDate(Date beginDate, String pattern, int num) {
        // 日期格式
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date parse = null;

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(beginDate);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - num);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        parse = calendar.getTime();
//        String format = sdf.format(calendar.getTime());
//        try {
//            parse = sdf.parse(format);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        return parse;
    }
}
